import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:syria_sports/presentation/attendances_list_page/models/attendance.dart';
import 'package:collection/collection.dart';

import '../data/apiClient/apis_data.dart';
import '../data/controllers/attendances_controller.dart';
import '../data/models/auth/user.dart';
import '../presentation/admin_home_tabs/cp_tab/models/home_model.dart';

FluffyGym? _selectedGym;
GymExercise? _selectedExercise;
DateTime selectedDateTime = DateTime.now();


class AddAttendanceDialog extends StatefulWidget {
  final User player;
  const AddAttendanceDialog({super.key, required this.player});

  @override
  State<AddAttendanceDialog> createState() => _AddAttendanceDialogState();
}

class _AddAttendanceDialogState extends State<AddAttendanceDialog> {
  DateFormat dateTimeFormatter = DateFormat('yyyy-MM-dd hh:mm a');


  @override
  void initState() {
    // TODO: implement initState
    _selectedGym = APISData.homeData.gyms.firstWhereOrNull((element) => element.gymId == _selectedGym?.gymId);
    _selectedExercise = _selectedGym?.exercises.firstWhereOrNull((element) => element.exerciseId == _selectedExercise?.exerciseId);


    //updateHomeData();
    super.initState();
  }



  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shadowColor: Colors.grey,
      elevation: 16,
      scrollable: true,
      backgroundColor: Theme.of(context).colorScheme.secondary,
      title: Text('إضافة حضور للاعب ${widget.player.fullName}'),
      content: SizedBox(
        height: MediaQuery.of(context).size.height/3,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Align(
                alignment: Alignment.centerRight,
                child: Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: Text('النادي:',style: theme.textTheme.bodySmall!.copyWith(fontSize: 16),),
                ),
              ),
              DropdownButton<FluffyGym>(
                value: _selectedGym,
                dropdownColor: Theme.of(context).colorScheme.secondary,
                isExpanded: true,
                hint: Text('اختر نادي',style: theme.textTheme.titleSmall,),
                onChanged: (value) {
                  setState(() {
                    _selectedGym = value;
                    _selectedExercise = null;

                  });
                },
                items: List.generate(APISData.homeData.gyms.length, (index) {
                  return DropdownMenuItem(
                    value: APISData.homeData.gyms[index],
                    child: Text(APISData.homeData.gyms[index].name,style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
                  );
                },
                ),
              ),
              Column(
                  children: [
                    const SizedBox(height: 8),
                    Align(
                      alignment: Alignment.centerRight,
                      child: Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: Text('التمرين:',style: theme.textTheme.bodySmall!.copyWith(fontSize: 16),),
                      ),
                    ),
                    DropdownButton<GymExercise>(
                      value: _selectedExercise,
                      dropdownColor: Theme.of(context).colorScheme.secondary,
                      isExpanded: true,
                      hint: Text('اختر التمرين',style: theme.textTheme.titleSmall,),
                      onChanged: (value) {
                        setState(() {
                          _selectedExercise = value;
                        });
                      },
                      items:(_selectedGym==null)?[]:List.generate(_selectedGym!.exercises.length, (index) =>
                          DropdownMenuItem(
                            value: _selectedGym!.exercises[index],
                            child: Text(_selectedGym!.exercises[index].name,style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
                          ),
                      ),
                    ),
                  ],
                ),
              const SizedBox(height: 16),
              Text('تاريخ ووقت الحضور:',style: theme.textTheme.bodySmall!.copyWith(fontSize: 16),),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(dateTimeFormatter.format(selectedDateTime)),
                  IconButton(
                      onPressed: (){
                        _selectDateTime(context);
                      },
                      icon: const Icon(Icons.edit_calendar_outlined, color: Colors.deepOrange,))
                ],
              ),

            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            if(_selectedGym != null && _selectedExercise != null) {
              addNote(widget.player);
              Navigator.pop(context);
            }else{
              showErrorMessage(message: 'الرجاء تحديد تمرين اولاً');
            }
          },
          child:  Text('إضافة',style :theme.textTheme.titleMedium),
        ),
        TextButton(
          onPressed: () {
            Navigator.of(context).pop(); // إغلاق الديالوج
          },
          child: Text('رجوع',style :theme.textTheme.titleMedium),
        ),
      ],
    );
  }

  void addNote(User note){
    if(_selectedExercise == null || _selectedGym == null ){
      showErrorMessage(message: 'الرجاء تحديد تمرين اولاً');
      return;
    }
    AttendancesController.addAttendance(
        Attendance(
          exerciseId: (_selectedExercise?.exerciseId)??'-1',
          userId: note.userId??'-1',
          attendanceId: (_selectedGym?.gymId)??'-1',
          datetime: selectedDateTime,
        )
    );
  }


  Future<void> _selectDateTime(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDateTime,
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData(
            fontFamily: 'Tajawal',
            visualDensity: VisualDensity.standard,
            colorScheme: const ColorScheme.dark().copyWith(
              primary: Colors.red, // تحديد اليوم بلون أحمر
            ),
            textButtonTheme: TextButtonThemeData(
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
              ),
            ),
          ),
          child: child!,
        );
      },
    );
    if (picked != null) {
      final TimeOfDay? pickedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(selectedDateTime),
        builder: (BuildContext context, Widget? child) {
          return Theme(
            data: ThemeData(
              fontFamily: 'Tajawal',
              visualDensity: VisualDensity.standard,
              colorScheme: const ColorScheme.dark().copyWith(
                primary: Colors.red, // تحديد اليوم بلون أحمر
              ),
              textButtonTheme: TextButtonThemeData(
                style: ButtonStyle(
                  foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
                ),
              ),
            ),
            child: child!,
          );
        },
      );
      if (pickedTime != null) {
        setState(() {
          selectedDateTime = DateTime(
            picked.year,
            picked.month,
            picked.day,
            pickedTime.hour,
            pickedTime.minute,
          );
        });
      }
    }
  }
}
